//
//  EmoticonController.swift
//  表情键盘
//
//  Created by 付建国 on 2016/10/19.
//  Copyright © 2016年 sher. All rights reserved.
//

import UIKit

fileprivate let EmoticonCell = "EmoticonCell"

class EmoticonController: UIViewController {
    
    // MARK:- 自定义属性
    var emoticonCallBack : (_ emoticon : Emoticon) -> ()
    
    // MARK:- 自定义函数
    fileprivate lazy var collectionView : UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: EmoticonCollectionViewLayout())
    fileprivate lazy var toolbar : UIToolbar = UIToolbar()
    fileprivate lazy var manager = EmoticonManager()
    
    // MARK:- 自定义构造函数
    init(emoticonCallBack : @escaping (_ emoticon : Emoticon) -> ()) {
        self.emoticonCallBack = emoticonCallBack
        super.init(nibName: nil, bundle: nil)
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }

}

// MARK:- 设置UI界面内容
extension EmoticonController{
    fileprivate func setupUI(){
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        collectionView.backgroundColor = UIColor.lightGray
        toolbar.backgroundColor = UIColor.green
        //设置frame(VFL)
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        
        let views = ["toolbar" : toolbar, "collectionView" : collectionView] as [String : Any]
        //水平约束
        var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[toolbar]-0-|", options: [], metrics: nil, views: views)
        //垂直约束
        cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[collectionView]-0-[toolbar]-0-|", options: [.alignAllLeft, .alignAllRight], metrics: nil, views: views)
        
        view.addConstraints(cons)
        //准备collectionView
        prepareCollectionview()
        //准备toolbar
        prepareToolbar()
        
    }
    
    fileprivate func prepareCollectionview() {
        //注册cell和数据源
        collectionView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: EmoticonCell)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    fileprivate func prepareToolbar(){
        //定义toolbar中的title
        let titles = ["最近", "默认", "emoji", "浪小花"]
        //遍历标题创建item
        var index = 0
        var tempItems = [UIBarButtonItem]()
        for title in titles {
            let item = UIBarButtonItem.init(title: title, style: .plain, target: self, action: #selector(itemClick(item:)))
            item.tag = index
            index += 1
            
            tempItems.append(item)
            //添加弹簧
            tempItems.append(UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        //设置toolbar的items
        tempItems.removeLast()
        toolbar.items = tempItems
        toolbar.tintColor = UIColor.orange
    }
    @objc fileprivate func itemClick(item : UIBarButtonItem){
        let tag = item.tag
        let indexPath = NSIndexPath.init(item: 0, section: tag)
        collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: true)
    }
    
}

// MARK:- 设置数据源和代理方法
extension EmoticonController : UICollectionViewDataSource, UICollectionViewDelegate{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = manager.packages[section]
        
        return package.emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! EmoticonCollectionViewCell
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        
        cell.emoticon = emoticon
        
        return cell
        
    }
    
    //代理方法
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //取出点击的表情
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        
        //将点击的表情插入到最近分组
        insertRecentlyEmoticon(emoticon: emoticon)
        
        //将表情回调给外界控制器
        emoticonCallBack(emoticon)
    }
    
    fileprivate func insertRecentlyEmoticon(emoticon : Emoticon){
        //如果是空白表情或者删除按钮，不需要插入
        if emoticon.isRemove || emoticon.isEmpty{
            return
        }
        //删除一个表情
        if manager.packages.first!.emoticons.contains(emoticon){
            //原来有这个表情
            let index = (manager.packages.first?.emoticons.index(of: emoticon))!
            manager.packages.first?.emoticons.remove(at: index)
        }else{
            //原来没有这个表情
            manager.packages.first?.emoticons.remove(at: 19)
        }
        //将emoticon插入分组中
        manager.packages.first?.emoticons.insert(emoticon, at: 0)
    }
}



class EmoticonCollectionViewLayout : UICollectionViewFlowLayout {
    
    override func prepare(){
        super.prepare()
        
        //计算itemWH
        let itemWH = UIScreen.main.bounds.size.width / 7
        //设置layout属性
        itemSize = CGSize.init(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .horizontal
        
        //设置collectionView的属性
        collectionView?.isPagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        let insetMargin = (collectionView!.bounds.height - 3 * itemWH) * 0.45
        collectionView?.contentInset = UIEdgeInsetsMake(insetMargin * 0.8, 0, insetMargin, 0)
    }
    
}










